package com.mcxx.modules.base.utils.excel;

import com.mcxx.common.exception.BizException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


public class ExcelUtil {

    public static Workbook getSheets(MultipartFile file) {
        Workbook workbook = null;

        String fileName = file.getOriginalFilename();

        String suffix = fileName.substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if (!suffix.equals("xlsx") && !suffix.equals("xls")) {
            throw new BizException("-1", "文件类型不正确，请选择xlsx或xls后缀文件");
        }

        assert fileName != null;
        if (fileName.endsWith("xls")) {
            try {

                workbook = new HSSFWorkbook(file.getInputStream());
            } catch (IOException e) {
                throw new BizException("-1", "文件格式不正确");
            }
        } else if (fileName.endsWith("xlsx")) {
            try {

                workbook = new XSSFWorkbook(file.getInputStream());
            } catch (IOException e) {
                throw new BizException("-1", "文件格式不正确");
            }
        }
        return workbook;
    }
}
